<!--
 * @Author: maomao
 * @Date: 2021-04-25 09:43:49
 * @Description: 
 * @FilePath: \client-app\src\components\header-bar.vue
-->
<template>
  <header class="header-component">
    <dx-toolbar class="header-toolbar">
      <!-- <dx-item location="before" css-class="menu-button">
        <template #default>
          <DxSelectBox
            v-model:value="selectCatalog"
            v-bind="selectSetting"
            @value-changed="onValueChange"
          />
        </template>
      </dx-item> -->
      <!-- <dx-item location="before">
        <template #default>
          <DxTextBox v-bind="searchSetting" v-model:value="searchCatalog" />
       
        </template>
      </dx-item>
      <dx-item location="before">
        <template #default>
          <DxButton v-bind="searchBtnSetting" />
        </template>
      </dx-item> -->
      <dx-item location="after" locate-in-menu="auto">
        <template #default>
          <div class="header-button-bar">
            <div style="color: #202020">
              系统使用方案：{{ selectItem ? selectItem.name : "" }}
            </div>
            <dx-selectBox
              v-model:value="selectSolution"
              v-bind="solutionSetting"
              @value-changed="onSolutionChange"
            />
            <dx-button
              class="user-button authorization"
              v-bind="choiceSetting"
              @click="choiceSolution"
            >
            </dx-button>
            <dx-button
              class="user-button authorization"
              v-bind="buttonSetting"
              @click="popupVisible = true"
            >
            </dx-button>
          </div>
        </template>
      </dx-item>
    </dx-toolbar>
    <DxPopup
      v-model:visible="popupVisible"
      :drag-enabled="false"
      :close-on-outside-click="true"
      :show-title="true"
      :width="300"
      :height="250"
      title="新增方案"
    >
      <div style="height: 20px"></div>
      <DxTextBox
        class="dx-field-value"
        width="100%"
        v-model:value="solutionName"
        styling-mode="outlined"
        @enterKey="addSolution"
        placeholder="请输入方案名"
      />
      <div class="lb-form-button">
        <DxButton
          :width="120"
          text="保存"
          type="default"
          styling-mode="text"
          @click="addSolution"
        />
        <DxButton
          :width="120"
          text="取消"
          type="default"
          styling-mode="text"
          @click="popupVisible = false"
        />
      </div>
    </DxPopup>
  </header>
</template>

<script lang="ts">
import DxToolbar, { DxItem } from "devextreme-vue/toolbar";
import DxButton from "devextreme-vue/button";
import DxSelectBox from "devextreme-vue/select-box";
import UserPanel from "./user-panel.vue";
import { Options, Vue } from "vue-class-component";
import { Emit, Inject, Prop, Watch } from "vue-property-decorator";
import { ApiTool } from "../api/api-tool";
import { ApiExceptionShow } from "../utils/api-exception-show";
import { dxSelectBoxOptions } from "devextreme/ui/select_box";
import { dxButtonOptions } from "devextreme/ui/button";
import {
  CatalogOutput,
  GetPagedCatalogInput,
  GetPagedSolutionInput,
  SolutionClient,
  SolutionOutput,
} from "@/api/api_solutionclient";
import { CatalogClient } from "@/api/api_catalogclient";
import { PageInfo } from "@/utils/page_utils";
import { SearchByURL } from "@/utils/search-byurl";
import { DxPopup } from "devextreme-vue/popup";
import DialogInputTitle from "@/components/dialog-input-title.vue";
import DxTextBox from "devextreme-vue/text-box";
import notify from "devextreme/ui/notify";
import { DialogUtil } from "@/utils/dialog-util";
import { Tool } from "@/utils/tool";
import ThemeSwitch from "@/framework/theme-switch/theme-switch";
import { dxTextBoxOptions } from "devextreme/ui/text_box";
@Options({
  components: {
    DxButton,
    DxToolbar,
    DxItem,
    DxSelectBox,
    UserPanel,
    DxPopup,
    DialogInputTitle,
    DxTextBox,
  },
  computed: {
    // 系统选中的方案
    selectItem() {
      return (
        this.solutionList.find((solution) => {
          if (solution.isCurrent == 1) {
            return solution;
          }
        }) ||
        this.solutionList.find((solution) => {
          if (solution.isDefault == 1) {
            return solution;
          }
        })
      );
    },
    // 用户当前展示方案
    showItem() {
      return this.solutionList.find((solution) => {
        if (solution.solutionId == this.selectSolution) {
          return solution;
        }
      });
    },
  },
})
export default class HeaderBar extends Vue {
  @Prop()
  title: string;

  @Prop()
  logOutFunc: Function;

  @Inject()
  apiTool: ApiTool;
  @Inject()
  themeSwitch: ThemeSwitch;
  @Emit("change")
  selectSolution = "";
  solutionName = "";
  popupVisible = false;
  showItem: SolutionOutput;
  selectItem: SolutionOutput;
  selectCatalog: CatalogOutput = null;
  searchCatalog: String = "";
  searchByUrl: SearchByURL = null;
  page: PageInfo = {
    index: 0,
    count: 0,
    pageSize: 100,
    pageCount: 0,
  };

  solutionFormData: GetPagedSolutionInput = {
    page: this.page,
  };

  catalogFormData: GetPagedCatalogInput = {
    page: this.page,
    solutionId: "",
    parentId: "",
    grade: 0,
  };

  solutionList: SolutionOutput[] = [];

  catlogList: CatalogOutput[] = [];

  searchSetting: dxTextBoxOptions = {
    mode: "search",
    placeholder: "请输入目录名称",
    stylingMode: "outlined",
    elementAttr: {
      class: "search-input",
    },
  };

  selectSetting: dxSelectBoxOptions = {
    width: 280,
    items: [],
    stylingMode: "outlined",
    displayExpr: "name",
    elementAttr: {
      class: "menu-bar",
    },
  };

  choiceSetting: dxButtonOptions = {
    stylingMode: "text",
    type: "normal",
    text: "启动当前选择方案",
    elementAttr: {
      class: "menu-bar",
    },
  };

  buttonSetting: dxButtonOptions = {
    stylingMode: "text",
    text: "新增方案",
    type: "normal",
    elementAttr: {
      class: "menu-bar",
    },
  };

  searchBtnSetting: dxButtonOptions = {
    text: '搜索',
    type: 'default',
    stylingMode: 'contained',
    height: 40,
    elementAttr: {
      class: 'search-button',
    }
  };

  solutionSetting: dxSelectBoxOptions = {
    items: [],
    stylingMode: "filled",
    text: "方案列表",
    valueExpr: "solutionId",
    displayExpr: "name",
    elementAttr: {
      class: "menu-bar",
    },
  };

  mounted() {
    this.searchByUrl = new SearchByURL(this.$router);
    this.onGetListSolution();
  }
  // 选择当前方案
  async choiceSolution() {
    if (!this.selectSolution) {
      notify("请先选择方案");
      return;
    }
    let res = await DialogUtil.confirm({
      content: `是否启用当前方案(${this.showItem.name})`,
    });
    if (!res) {
      return;
    }
    let client = this.apiTool.createClient(SolutionClient);
    client
      .checkIsCurrent(this.selectSolution)
      .then((result) => {
        if (result.isSuccess) {
          notify("切换启用方案成功", "success", 2000);
          this.onGetListSolution();
        } else {
          notify(result.message, "error", 2000);
        }
      })
      .catch((error) => {
        notify("系统异常", "error");
      });
  }
  // 添加方案
  addSolution() {
    if (!this.solutionName) {
      notify("请输入方案名");
      return;
    }
    let client = this.apiTool.createClient(SolutionClient);
    const defaultSolution = this.solutionList.find((item) => {
      if (item.isDefault == 1) return item;
    });
    client
      .insertOrUpdateSolution({
        name: this.solutionName,
        copySolutionId: defaultSolution.solutionId,
      })
      .then((result) => {
        if (result.isSuccess) {
          notify("添加方案成功", "success", 2000);
          this.onGetListSolution();
          this.popupVisible = false;
        } else {
          notify(result.message, "error", 2000);
        }
      })
      .catch(() => {
        notify("系统异常", "error");
      });
  }

  onSearchChanged(e) {
    console.log("搜索事件", e.value);
  }
  /** 获取字典方案 */
  onGetListSolution() {
    let client = this.apiTool.createClient(SolutionClient);
    client
      .getListSolution(this.solutionFormData)
      .then((model) => {
        this.solutionList = model.listData;
        let solutionId = this.$route.query.solutionId as string;
        let findItem: SolutionOutput = null;

        findItem = this.solutionList.find((_val) => {
          if (solutionId === _val.solutionId) {
            return _val;
          }
        });

        if (findItem == null) {
          findItem = this.solutionList.find((_val) => {
            if (_val.isCurrent === 1) {
              return _val;
            }
          });
        }

        if (findItem == null) {
          findItem = this.solutionList.find((_val) => {
            if (_val.isDefault === 1) {
              return _val;
            }
          });
        }

        //  _val.isCurrent === 1 || _val.isDefault === 1
        this.selectSolution = findItem.solutionId;

        this.solutionSetting.items = this.solutionList;
        // this.onGetListCatalog();
      })
      .catch((error) => {
        ApiExceptionShow.showException(error, this, "");
      });
  }

  /** 获取字典目录 */
  async onGetListCatalog() {
    this.catalogFormData.solutionId = this.selectSolution;
    let client = this.apiTool.createClient(CatalogClient);
    client
      .getListCatalog(this.catalogFormData)
      .then((model) => {
        this.catlogList = model.listData;
        let item: CatalogOutput = {
          name: "全部",
          grade: 0,
          solutionId: this.selectSolution,
          parentId: "",
          catalogId: "",
        };
        this.catlogList.unshift(item);
        this.selectSetting.items = this.catlogList;
        let treeIds = this.$route.query.treeIds as string;
        let treeId = treeIds.split("@")[0];
        if (treeIds && !Tool.isEmpty(treeId)) {
          this.selectCatalog = this.catlogList.find((_val) => {
            if (treeId) {
              return treeId === _val.catalogId;
            }
          });
        } else {
          this.selectCatalog = this.catlogList[0];
        }
      })
      .catch((error) => {
        ApiExceptionShow.showException(error, this);
      });
  }

  onProfileClick() {
    this.$router.push({
      path: "/profile",
      query: { redirect: this.$route.path },
    });
  }

  onValueChange(e: { value: CatalogOutput }) {
    let form = {
      solutionId: e.value.solutionId,
      catalogId: e.value.catalogId,
      treeIds: e.value.catalogId,
    };

    this.searchByUrl.setParamsToUrl(form);
    form["grade"] = e.value.grade + 1;
    this.$emit("change", form);
  }

  onSolutionChange(e) {
    this.selectSolution = e.value;
    let solutionId = this.$route.query.solutionId as string;
    let reset = this.selectSolution != solutionId;
    // if (this.selectSolution != solutionId) {
    //   let form = {
    //     solutionId: e.value.solutionId,
    //     catalogId: "",
    //     treeIds: "",
    //   };
    //   this.searchByUrl.setParamsToUrl(form);
    // }
    // this.onGetListCatalog();

    // 临时改动 直接传值到菜单树 start
    let form = {
      solutionId: reset ? this.selectSolution : solutionId,
      catalogId: reset ? "" : (this.$route.query.catalogId as string) ?? "",
      treeIds: reset ? "" : (this.$route.query.treeIds as string) ?? "",
    };
    this.searchByUrl.setParamsToUrl(form);
    form["grade"] = 0;
    // 临时改动 直接传值到菜单树 end

    this.$emit("change", form);
  }
}
</script>

<style lang="scss">
@import "../themes/generated/variables.base.scss";
@import "../dx-styles.scss";
.menu-bar {
  margin-left: 20px;
}

.search-input {
  margin-left: 20px;
}

.search-button {
  padding: 8px 0 !important;
}

.header-button-bar {
  display: flex;
  justify-content: center;
  align-items: center;
}
.header-component {
  flex: 0 0 auto;
  z-index: 1;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
  .dx-toolbar .dx-toolbar-item.menu-button > .dx-toolbar-item-content .dx-icon {
    color: $base-accent;
  }
}

.dx-toolbar.header-toolbar .dx-toolbar-items-container .dx-toolbar-after {
  padding: 0 40px;
  .screen-x-small & {
    padding: 0 20px;
  }
}

.dx-toolbar .dx-toolbar-item.dx-toolbar-button.menu-button {
  width: $side-panel-min-width;
  text-align: center;
  padding: 0;
}

.header-title .dx-item-content {
  padding: 10px;
  margin: 0;
  font-size: 16px;
}

.dx-theme-generic {
  .dx-toolbar {
    padding: 10px 0;
  }

  .user-button {
    margin-left: 20px;
  }

  .user-button > .dx-button-content {
    padding: 3px;
  }
}
</style>
